<?php

class HopDong extends Database
{
    public function getHopDong($id)
    {
        $sql = <<<SQL
SELECT hd.hd_id, lhd_mota, hd_ngaybd, hd_ngaykt, ct.cb_id
FROM hopdong hd NATURAL JOIN loai_hopdong NATURAL JOIN chitiethd ct
WHERE ct.cb_id = :id
SQL;
        return $this->run($sql, array('id' => $id));
    }

    public function getHopDongById($id)
    {
        $sql = <<<sql
        SELECT hd.hd_id, lhd_mota, l.lhd_id, DATE_FORMAT(hd_ngaybd, '%d/%m/%Y') AS hd_ngaybd, DATE_FORMAT(hd_ngaykt, '%d/%m/%Y') AS hd_ngaykt, ct.cb_id
FROM hopdong hd NATURAL JOIN loai_hopdong l NATURAL JOIN chitiethd ct
WHERE hd.hd_id = :id
sql;
        $data = $this->run($sql, array('id' => $id));
        if (count($data) > 0) {
            return $data[0];
        } else {
            return false;
        }
    }

    public function them($cb_id, $lhd_id, $ngaybd, $ngaykt)
    {
        $sql = <<<sql
INSERT INTO hopdong(lhd_id, hd_ngaybd, hd_ngaykt) VALUES(:lhd_id, :ngaybd, :ngaykt)
sql;
        $this->run($sql, array(
            'lhd_id' => $lhd_id,
            'ngaybd' => $ngaybd,
            'ngaykt' => $ngaykt
        ));

        $hd_id = $this->lastInsertId();

        $this->run('INSERT INTO chitiethd(cb_id, hd_id) VALUES(:cb_id, :hd_id)', array(
            'cb_id' => $cb_id,
            'hd_id' => $hd_id
        ));

        return $hd_id;
    }

    public function xoa($cb_id, $hd_id)
    {
        $sql = <<<SQL
DELETE FROM chitiethd WHERE cb_id = :cb_id AND hd_id = :hd_id
SQL;
        $this->run($sql, array(
            'cb_id' => $cb_id,
            'hd_id' => $hd_id
        ));

        $this->run('DELETE FROM hopdong WHERE hd_id = :id', array('id' => $hd_id));
    }

    public function sua($hd_id, $lhd_id, $ngaybd, $ngaykt)
    {
        $sql = <<<sql
UPDATE hopdong SET lhd_id = :lhd, hd_ngaybd = :ngaybd, hd_ngaykt = :ngaykt WHERE hd_id = :id
sql;

        $this->run($sql, array(
            'lhd' => $lhd_id,
            'ngaybd' => $ngaybd,
            'ngaykt' => $ngaykt,
            'id' => $hd_id
        ));
    }
}
